package guoanmaker.provider.business.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import guoanmaker.provider.business.model.OperatorSecckill;
import guoanmaker.provider.business.model.OperatorServerClass;
import guoanmaker.provider.business.model.PersonalCollection;
import guoanmaker.provider.business.model.ProvideCity;
import guoanmaker.provider.business.model.ProvideCommodity;
import guoanmaker.provider.business.model.ProvideSpacefacilities;
import guoanmaker.provider.business.modelnobind.ProvideCommodityMove;
import guoanmaker.provider.business.modelnobind.ProvideCommodityServiceMove;
import guoanmaker.provider.business.modelnobind.ProvideRoomMove;
import guoanmaker.provider.business.repository.OperatorSecckillRepository;
import guoanmaker.provider.business.repository.OperatorServerClassRepository;
import guoanmaker.provider.business.repository.PersonalCollectionRepository;
import guoanmaker.provider.business.repository.ProvideCityRepository;
import guoanmaker.provider.business.repository.ProvideCommodityRepository;
import guoanmaker.provider.business.repository.ProvideSpacefacilitiesRepository;

@Service
public class ProvideCommodityMoveService implements ProvideCommodityMoveServiceInterface{
	
	@Autowired
	private ProvideCommodityRepository commodityMoveRepository;
	
	@Autowired
	private OperatorServerClassRepository provideServerClassRepository;
	
	@Autowired
	private ProvideCityRepository provideCityRepository;
	
	@Autowired
	private ProvideCityRepository cityRepository;
	
	@Autowired
	private ProvideSpacefacilitiesRepository provideSpacefacilitiesRepository;
	
	@Autowired
	private PersonalCollectionRepository personalCollectionRepository;
	
	@Autowired
	private OperatorSecckillRepository secckillRepository;
	
	@PersistenceContext
	private EntityManager manager;

	/**
	* @Title: selectProvideCommodityMoves 
	* @Description: 分页查询商品列表
	* @param  page 当前页
	* @param  size 显示条数
	* @param  service_type_id(类型)
	* @param  code 当前城市code
	* @param reorderType排序条件 0:默认查询 1:商品评价数量 2:点击量由高到低排序 3:按照商品价格由低到高排序 4:按照商品价格由高到低排序 5:按照商品销量由高到低排序 6:按照商品销量由低到高排序
	* @param serverClass 经营范围
	* @return Map<String,Object>    返回类型 
	* @throws 
	 */
	@Override
	public Map<String, Object> selectProvideCommodityMoves(Integer page, Integer size, String service_type_id,String code,Integer type,Integer indexXb,Integer reorderType,OperatorServerClass serverClass) {
		Map<String, Object> reMap=new HashMap<>();
		//OperatorServerClass serverClass=provideServerClassRepository.findOne(service_type_id);//通过分类id获取分类对象
		List<String> ids=new ArrayList<>();
		if(serverClass!=null){
			if(serverClass.getServerLevel()==2){
				//查询三级基础数据
				List<OperatorServerClass> servers=null;
				servers=provideServerClassRepository.findAllByParentServerId(service_type_id);
				reMap.put("servers", servers);
			}
			Integer serverLevel=serverClass.getServerLevel();
			ArrayList<OperatorServerClass> provideServerClassArrayList = provideServerClassRepository.findAllByParentServerId(service_type_id);//获取二级或者三级下面的子标签
			if(provideServerClassArrayList!=null && provideServerClassArrayList.size()>0){
				for(int i=0;i<provideServerClassArrayList.size();i++){
					if(serverLevel==2){
						String parentId=provideServerClassArrayList.get(i).getId();//三级id
						ArrayList<OperatorServerClass> threeList = provideServerClassRepository.findAllByParentServerId(parentId);
						if(threeList!=null && threeList.size()>0){//如果三级分类下面存在四级分类，则将四级分类id放入ids集合；否则将当前三级分类id放入ids集合中
							for(int j=0;j<threeList.size();j++){
								ids.add(threeList.get(j).getId());
							}
						}else{
							ids.add(parentId);
						}
					}else{
						ids.add(provideServerClassArrayList.get(i).getId());
					}
				}
			}else{
				ids.add(service_type_id);
			}
		}else{
			ids.add(service_type_id);
		}
		String sort="";//地区排序规则
		String sort1="";//全国排序规则
		if(reorderType==6){ //按照销量排序
			sort=" order by t1.salesVolume asc";
			sort1=" order by t.salesVolume asc";
		}else if(reorderType==5){ //按照销量排序
			sort=" order by t1.salesVolume desc";
			sort1=" order by t.salesVolume desc";
		}else if(reorderType==2){//按照点击量排序
			sort=" order by t1.clickRate desc";
			sort1=" order by t.clickRate desc";
		}else if(reorderType==3){
			sort=" order by t.finalPrice asc";
			sort1=" order by t.finalPrice asc";
		}else if(reorderType==4){
			sort=" order by t.finalPrice desc";
			sort1=" order by t.finalPrice desc";
		}else if(reorderType==1){
			sort="order by t1.evaluateValue desc";
			sort1=" order by t.evaluateValue desc";
		}
		String jl="select new guoanmaker.provider.business.modelnobind.ProvideCommodityMove("
					+ "t1.commodityName,b.businessName,t1.isBargaining,t1.startingPrice,d.dictName,t1.invoiceMail,t1.isTerritoryRestriction"
					+ ",t1.commodityPrice,t1.commodityPricePromotion,t1.startTime,t.endTime,t1.commodity_bigimage,t1.description,t1.commodityState,t1.releaseTime,t1.stock"
					+ ",t1.populationRestriction,t1.registrationStartTime,t1.registrationEndTime,t1.synopsis,t1.id,t1.type,sv.serverName,t1.isPromotion,t1.clickRate"
					+ ",b.companyCity,t1.commodity_smallimage,t1.salesVolume,MIN(t.finalPrice),t1.evaluateValue) from ProvideCommodityServiceRange t left join t.commodity t1 left join t.city c "
					+ "left join t1.providerBusiness b  left join t1.measurementUnit d   "
				+ "left join t1.serviceType sv where t1.commodityState=2 and c.code=:code  ";
		if(ids.size()>0){
			String str=getServiceType(ids);
			jl=jl+("and sv.id in (")+str+")  group by t1.id "+sort;
		}else{
			jl=jl+" group by t.id "+sort;
		}
		Query query=manager.createQuery(jl);//查询商品列表
		query.setParameter("code", code);
		query.setFirstResult((page-1)*size);
		query.setMaxResults(size);
		List<ProvideCommodityMove> commodityMoves=query.getResultList();
		if(type==3 || type==1){
			System.out.println("不处理");
		}else if(commodityMoves.size()==0 && page==1){
			type=1;
		}else if(commodityMoves.size()<size && page==1){
			type=2;
		}else if(commodityMoves.size()==0 && page>1 ){
			type=3;
		}else if(commodityMoves.size()<size && page>1){
			type=4;
		}
		if(commodityMoves.size()<size){//如果地区商品不能满足搜索的条数，则去全国商品列表查询数据
			String jql="select new guoanmaker.provider.business.modelnobind.ProvideCommodityMove("
					+ "t.commodityName,b.businessName,t.isBargaining,t.startingPrice,d.dictName,t.invoiceMail,t.isTerritoryRestriction"
					+ ",t.commodityPrice,t.commodityPricePromotion,t.startTime,t.endTime,t.commodity_bigimage,t.description,t.commodityState,t.releaseTime,t.stock"
					+ ",t.populationRestriction,t.registrationStartTime,t.registrationEndTime,t.synopsis,t.id,t.type,sv.serverName,t.isPromotion,t.clickRate"
					+ ",b.companyCity,t.commodity_smallimage,t.salesVolume,MIN(t.finalPrice),t.evaluateValue) "
					+ "from ProvideCommodity t left join t.providerBusiness b  left join t.measurementUnit d left join t.serviceType sv"
					+ " where  t.commodityState=2 and t.isTerritoryRestriction='2'  ";
			if(ids.size()>0){
				String str=getServiceType(ids);
				jql=jql+("and sv.id in (") +str+")  group by t.id "+ sort1;
			}else{
				jql=jql+" group by t.id "+ sort1;
			}
			Query query2=manager.createQuery(jql);//查询全国商品列表
			if(type==1){
				query2.setFirstResult((page-1)*size);
				query2.setMaxResults(size);
			}else if(type==2){
				int qishi=commodityMoves.size();//起始值
				int cha=size-commodityMoves.size();//需要查询的数据条数
				query2.setFirstResult(0);
				query2.setMaxResults(cha);
				indexXb=cha;//下次起始值
				type=3;
			}else if(type==3){
				query2.setFirstResult(indexXb);
				query2.setMaxResults(size);
				indexXb=indexXb+size;//下次起始值
			}else if(type==4){
				int qishi=commodityMoves.size();//起始值
				int cha=size-commodityMoves.size();//需要查询的数据条数
				query2.setFirstResult(qishi);
				query2.setMaxResults(cha);
				indexXb=cha;//下次起始值
				type=3;
			}
			List<ProvideCommodityMove> commoditys2=query2.getResultList();
			if(commoditys2.size()>0){
				for(ProvideCommodityMove commodity: commoditys2){
					commodityMoves.add(commodity);
				}
			}
		}
		if(commodityMoves.size()==size){
			reMap.put("isLoading",1);
		}else{
			reMap.put("isLoading",2);
		}
		reMap.put("regionStart",indexXb);
		reMap.put("countrywideStart",type);
		reMap.put("commoditys",commodityMoves);
		
		if(commodityMoves.size()>0){
			for(int i=0;i<commodityMoves.size();i++){
				String cityCode=commodityMoves.get(i).getCompanyCity();//城市code
				ProvideCity city=cityRepository.findByCode(cityCode);
				commodityMoves.get(i).setCompanyCity(city.getName());
				commodityMoves.get(i).setLicensPhone("4008518585");
			}
			if(indexXb>0){
				Collections.sort(commodityMoves, new Comparator<ProvideCommodityMove>() {
					@Override
					public int compare(ProvideCommodityMove o1,ProvideCommodityMove o2){
						if(reorderType==4){
							if(o2.getFinalPrice()>o1.getFinalPrice()){
								return 1;
							}
							if(o1.getFinalPrice()==o2.getFinalPrice()){
								return 0;
							}
						}else if(reorderType==3){
							if(o1.getFinalPrice()>o2.getFinalPrice()){
								return 1;
							}
							if(o1.getFinalPrice()==o2.getFinalPrice()){
								return 0;
							}
						}else if(reorderType==5){
							if(o2.getSalesVolume()>o1.getSalesVolume()){
								return 1;
							}
							if(o1.getSalesVolume()==o2.getSalesVolume()){
								return 0;
							}
						}else if(reorderType==6){
							if(o1.getSalesVolume()>o2.getSalesVolume()){
								return 1;
							}
							if(o1.getSalesVolume()==o2.getSalesVolume()){
								return 0;
							}
						}else if(reorderType==2){
							if(o2.getClickRate()>o1.getClickRate()){
								return 1;
							}
							if(o1.getClickRate()==o2.getClickRate()){
								return 0;
							}
						}else if(reorderType==1){
							if(o2.getEvaluateValue()>o1.getEvaluateValue()){
								return 1;
							}
							if(o1.getEvaluateValue()==o2.getEvaluateValue()){
								return 0;
							}
						}
						return -1;
					}
				});
			}
		}

		return reMap;
		
	}
	
	
	/**
	 * 通过主键id获取商品信息
	 * @param id(商品表主键)
	 * @param cityCode(地级市code)
	 * @param userId(用户id)
	 * @param secckillId(秒杀规则id)
	 * @return 商品对象
	 * */
	@Override
	public ProvideCommodityMove selectById(String id,String cityCode,String userId,String secckillId) {
		String jpql="select new guoanmaker.provider.business.modelnobind.ProvideCommodityMove( "
				+ "t.commodityName,b.businessName,t.isBargaining,t.startingPrice,d.dictName,t.invoiceMail,t.isTerritoryRestriction"
				+ ",t.commodityPrice,t.commodityPricePromotion,t.startTime,t.endTime,t.commodity_bigimage,t.description,t.commodityState,t.releaseTime,t.stock"
				+ ",t.populationRestriction,t.registrationStartTime,t.registrationEndTime,t.synopsis,t.id,t.type,sv.serverName,t.isPromotion,t.clickRate,t.process"
				+ ",t.promise,t.commodityCase,t.auditOpinion,t.finalPrice,t.introduce,t.commodity_smallimage,b.LicensPhone,t.salesVolume) "
				+ " from ProvideCommodity t  left  join t.providerBusiness b left join t.serviceType  sv"
				+ " left join t.measurementUnit d    where  t.id=:id ";
		
		Query query=manager.createQuery(jpql);//查询商品信息
		query.setParameter("id", id);
		List<ProvideCommodityMove> comms= query.getResultList();
		ProvideCommodityMove commodity=null;
		if(comms.size()>0){
			commodity=comms.get(0);
			String jpql2="select new guoanmaker.provider.business.modelnobind.ProvideCommodityServiceMove(s.id,ct.code,a.name,ct.name,p.name,ct.provincecode,s.isPromotion,s.commodityPrice,s.commodityPricePromotion,s.startTime,s.endTime,s.finalPrice)"
					+ " from ProvideCommodityServiceRange s left join  s.commodity c left join s.city ct left join s.area a left join s.province p  where  c.id=:id and ct.code=:code order by s.finalPrice";
			Query query2=manager.createQuery(jpql2);//查询商品提供的服务区域
			query2.setParameter("id", commodity.getId());
			query2.setParameter("code", cityCode);
			List<ProvideCommodityServiceMove> lists=query2.getResultList();
			commodity.setServiceRange(lists);
			if(lists.size()>0){
				commodity.setFinalPrice(lists.get(0).getFinalPrice());
			}
			
			String commodityId=commodity.getId();
			if(StringUtils.isNotEmpty(userId)){
				List<PersonalCollection> commodityCollection=personalCollectionRepository.findByPersonalUser_idIsAndProvideCommodity_idIs(userId, commodityId);
				if(commodityCollection.size()>0){
					commodity.setIsCollection(1);
				}else{
					commodity.setIsCollection(2);
				}
			}else{
				commodity.setIsCollection(2);
			}
			commodity.setLicensPhone("4008518585");
			commodity.setIsSeckill(1);//默认商品不是秒杀商品
			if(secckillId!=null && !secckillId.equals("")){
				OperatorSecckill  secckill=secckillRepository.findById(secckillId);
				if(secckill!=null){
					Integer skNum=secckill.getSkNum();//秒杀商品数量
					Date skStartTime=secckill.getSkStartTime();//秒杀开始时间
					Date skEndTime=secckill.getSkEndTime();//秒杀结束时间
					String comId=secckill.getCommodId();//商品id
					Double skPrice=secckill.getSkPrice();//秒杀价格
					if(!comId.equals(id)){//验证是否同一商品。如果不是则默认是不秒杀商品
						return commodity;
					}
					long shij=new Date().getTime();//获取当前时间
					if(skNum>0 && shij>=skStartTime.getTime() && shij<=skEndTime.getTime()){
						commodity.setIsSeckill(2);//设置商品是秒杀商品
						commodity.setFinalPrice(skPrice);
						commodity.setSecckillId(secckillId);
					}
				}
			}
		}
		
		return commodity;
	}

	/**
	 * 获取服务类型id串
	 * @author baixsh
	 * @param  ids(类型主键集合)
	 * */
	public static String getServiceType(List<String> ids){
		String str="";
		if(ids!=null){
			for(int k=0;k<ids.size();k++){
				if(k==0){
					str=str+"'"+ids.get(k)+"'";
				}else{
					str=str+",'"+ids.get(k)+"'";
				}
			}
		}
		return str;
	}


	/***
	 * 统计商品访问点击量
	 * @author baixsh
	 * 
	 */
	@Override
	@Transactional
	public void countCommditysClickRate(String id) {
		String hql="select s from ProvideCommodity s where s.id=:id";
		Query query=manager.createQuery(hql);//查询商品信息
		query.setParameter("id", id);
		List<ProvideCommodity> comms= query.getResultList();
		if(comms.size()>0){
			ProvideCommodity comm=comms.get(0);
			Integer clickRate=comm.getClickRate();
			if(clickRate==null){
				clickRate=1;
			}else{
				clickRate++;
			}
			hql="update  ProvideCommodity set clickRate="+clickRate+" where id=:id";
			Query query2=manager.createQuery(hql);//修改点击量
			query2.setParameter("id", id);
			int result=query2.executeUpdate();
			System.out.println(result);
		}
	}


	/***
	* @Title: selectProvideRoom 
	* @Description: 通过城市code获取空间列表
	* @param cityCode    城市标识 
	* @param page 当前页数
	* @param size 每页条数
	* @return Map<String,Object>    返回类型 
	* @throws 
	 */
	@Override
	public List<ProvideRoomMove>  selectProvideRoom(String cityCode, Integer page, Integer size) {
		String jpql="select new  guoanmaker.provider.business.modelnobind.ProvideRoomMove(rm.id,rm.roomName,rm.describeAsk,rm.address,rm.lat,"
				+ "rm.lng,c.name,a.name,p.name,rm.spaceDetail,rm.roomImgOne,rm.roomImgTwo,rm.roomImgThree,rm.roomImgFour,rm.roomImgFive,rm.roomlogo,rm.complement) "
				+ " from ProvideRoom rm left join rm.city c left join rm.area a"
				+ " left join rm.province p where rm.roomState=2 and c.code=:code ";
		
		Query query=manager.createQuery(jpql);//查询商品信息
		query.setParameter("code", cityCode);
		query.setFirstResult((page-1)*size);
		query.setMaxResults(size);
		List<ProvideRoomMove> comms= query.getResultList();
		return comms;
	}


	/***
	* @Title: selectByRoomId 
	* @Description: 通过空间主键获取空间下面的商品
	* @param  roomId
	* @return List<ProvideCommodityMove>    返回类型 
	* @throws 
	 */
	@Override
	public Map<String,Object> selectByRoomId(String roomId) {
		Map<String,Object> reMap=new HashMap<String,Object>();
		List<OperatorServerClass> lists=provideServerClassRepository.findByServerLevelAndServerTypeAndDeleteStateIs(2, 1,"0");
		if(lists.size()>0){
			for(int i=0;i<lists.size();i++){
				String serverId=lists.get(i).getId();
				String jpql="select new guoanmaker.provider.business.modelnobind.ProvideCommodityMove( "
						+ "t.commodityName,b.businessName,t.isBargaining,t.startingPrice,d.dictName,t.invoiceMail,t.isTerritoryRestriction"
						+ ",t.commodityPrice,t.commodityPricePromotion,t.startTime,t.endTime,t.commodity_bigimage,t.description,t.commodityState,t.releaseTime,t.stock"
						+ ",t.populationRestriction,t.registrationStartTime,t.registrationEndTime,t.synopsis,t.id,t.type,sv.serverName,t.isPromotion,t.clickRate,t.process"
						+ ",t.promise,t.commodityCase,t.auditOpinion,t.finalPrice,t.introduce,t.commodity_smallimage,b.LicensPhone) "
						+ " from ProvideCommodity t  left  join t.providerBusiness b left join t.serviceType  sv"
						+ " left join t.measurementUnit d left join t.romm rm    where t.commodityState=2 and  rm.id=:id and sv.id=:serverId";
				
				Query query=manager.createQuery(jpql);//查询商品列表信息
				query.setParameter("id", roomId);
				query.setParameter("serverId", serverId);
				List<ProvideCommodityMove> comms= query.getResultList();
				lists.get(i).setCommoditys(comms);
			}
		}
		reMap.put("commoditys", lists);
		String jpql2="select new  guoanmaker.provider.business.modelnobind.ProvideRoomMove(rm.id,rm.roomName,rm.describeAsk,rm.address,rm.lat,"
				+ "rm.lng,c.name,a.name,p.name,rm.spaceDetail,rm.roomImgOne,rm.roomImgTwo,rm.roomImgThree,rm.roomImgFour,rm.roomImgFive,rm.roomlogo,rm.complement) "
				+ " from ProvideRoom rm left join rm.city c left join rm.area a"
				+ " left join rm.province p where rm.roomState=2 and rm.id=:id ";
		
		Query query2=manager.createQuery(jpql2);//查询商品信息
		query2.setParameter("id", roomId);
		List<ProvideRoomMove> rooms= query2.getResultList();
		if(rooms.size()>0){
			ProvideRoomMove roomMove=rooms.get(0);
			String complement=roomMove.getComplement();//配套
			List<String> userList = Arrays.asList(complement.split(","));
			List<ProvideSpacefacilities> spacefacilities=provideSpacefacilitiesRepository.findByIdIn(userList);
			roomMove.setSpacefacilities(spacefacilities);
			reMap.put("room",roomMove);
		}else{
			reMap.put("room", null);
		}
		return reMap;
	}
	




	@Override
	public Map<String,Object> selectKeyNameCodeSpaceCommodity(String code, String keyName) {
		keyName=keyName==null?"":keyName;
		Map<String,Object> map=new HashMap<String,Object>();
		
		String jpql="select new  guoanmaker.provider.business.modelnobind.ProvideRoomMove(rm.id,rm.roomName,rm.describeAsk,rm.address,rm.lat,"
				+ "rm.lng,c.name,a.name,p.name,rm.spaceDetail,rm.roomImgOne,rm.roomImgTwo,rm.roomImgThree,rm.roomImgFour,rm.roomImgFive,rm.roomlogo,rm.complement) "
				+ " from ProvideRoom rm left join rm.city c left join rm.area a"
				+ " left join rm.province p where rm.roomState=2 and c.code=:code  and rm.roomName like :keyName";
		
		
		Query query=manager.createQuery(jpql);//查询商品信息
		query.setParameter("code", code);
		query.setParameter("keyName","%"+keyName+"%");
		List<Object> listProvideRoom= query.getResultList();
		map.put("listProvideRoom", listProvideRoom);
		String jpql1="select new guoanmaker.provider.business.modelnobind.ProvideCommodityMove("
					+ "t1.commodityName,t1.isBargaining,t1.startingPrice,t1.invoiceMail,t1.isTerritoryRestriction"
					+ ",t1.commodityPrice,t1.commodityPricePromotion,t1.startTime,t1.endTime,t1.commodity_bigimage,t1.description,t1.commodityState,t1.releaseTime,t1.stock"
					+ ",t1.populationRestriction,t1.registrationStartTime,t1.registrationEndTime,t1.synopsis,t1.id,t1.type,t1.isPromotion,t1.clickRate"
					+ ",t1.commodity_smallimage,t1.salesVolume,t1.finalPrice,b.companyCity,b.LicensPhone,t1.promise) "
					+ " from ProvideCommodity t1 left join t1.providerBusiness b where t1.commodityState=2 and type!=1 and t1.isTerritoryRestriction=2  and t1.commodityName like :keyName";
		
		Query query1=manager.createQuery(jpql1);//查询全国商品信息
		query1.setParameter("keyName","%"+keyName+"%");
		List<ProvideCommodityMove> listProvideCommodityMove= query1.getResultList();
		String jpql2="select new guoanmaker.provider.business.modelnobind.ProvideCommodityMove("
				+ "t1.commodityName,b.businessName,t1.isBargaining,t1.startingPrice,d.dictName,t1.invoiceMail,t1.isTerritoryRestriction"
				+ ",t1.commodityPrice,t1.commodityPricePromotion,t1.startTime,t.endTime,t1.commodity_bigimage,t1.description,t1.commodityState,t1.releaseTime,t1.stock"
				+ ",t1.populationRestriction,t1.registrationStartTime,t1.registrationEndTime,t1.synopsis,t1.id,t1.type,sv.serverName,t1.isPromotion,t1.clickRate"
				+ ",b.companyCity,t1.commodity_smallimage,t1.salesVolume,MIN(t.finalPrice),t1.promise,b.LicensPhone) from ProvideCommodityServiceRange t left join t.commodity t1 left join t.city c "
				+ "left join t1.providerBusiness b  left join t1.measurementUnit d   "
			+ "left join t1.serviceType sv where t1.commodityState=2 and t1.isTerritoryRestriction=1 and c.code=:code  and t1.commodityName like :keyName GROUP BY t1.id";
		
		Query query2=manager.createQuery(jpql2);//查询商品信息
		query2.setParameter("code", code);
		query2.setParameter("keyName","%"+keyName+"%");
		List<ProvideCommodityMove> listProvideCommodityMove2= query2.getResultList();
		listProvideCommodityMove.addAll(listProvideCommodityMove2);
		if(listProvideCommodityMove.size()>0){
			for(int i=0;i<listProvideCommodityMove.size();i++){
				String cityCode=listProvideCommodityMove.get(i).getCompanyCity();//城市code
				if(cityCode!=null){
					ProvideCity city=cityRepository.findByCode(cityCode);
					listProvideCommodityMove.get(i).setCompanyCity(city.getName());
				}
				listProvideCommodityMove.get(i).setLicensPhone("4008518585");
			}
		}
		map.put("listProvideCommodityMove", listProvideCommodityMove);
		return map;
	}


	/***
	* @Title: selectByRoomCode 
	* @Description: 通过空间code获取空间下面的商品
	* @param  roomId
	* @return List<ProvideCommodityMove>    返回类型 
	* @throws 
	 */
	@Override
	public Map<String, Object> selectByRoomCode(String roomCode) {
		Map<String,Object> reMap=new HashMap<String,Object>();
		List<OperatorServerClass> lists=provideServerClassRepository.findByServerLevelAndServerTypeAndDeleteStateIs(2, 1,"0");
		if(lists.size()>0){
			for(int i=0;i<lists.size();i++){
				String serverId=lists.get(i).getId();
				String jpql="select new guoanmaker.provider.business.modelnobind.ProvideCommodityMove( "
						+ "t.commodityName,b.businessName,t.isBargaining,t.startingPrice,d.dictName,t.invoiceMail,t.isTerritoryRestriction"
						+ ",t.commodityPrice,t.commodityPricePromotion,t.startTime,t.endTime,t.commodity_bigimage,t.description,t.commodityState,t.releaseTime,t.stock"
						+ ",t.populationRestriction,t.registrationStartTime,t.registrationEndTime,t.synopsis,t.id,t.type,sv.serverName,t.isPromotion,t.clickRate,t.process"
						+ ",t.promise,t.commodityCase,t.auditOpinion,t.finalPrice,t.introduce,t.commodity_smallimage,b.LicensPhone) "
						+ " from ProvideCommodity t  left  join t.providerBusiness b left join t.serviceType  sv"
						+ " left join t.measurementUnit d left join t.romm rm    where t.commodityState=2 and  rm.roomCodes=:roomCodes and sv.id=:serverId";
				
				Query query=manager.createQuery(jpql);//查询商品列表信息
				query.setParameter("roomCodes", roomCode);
				query.setParameter("serverId", serverId);
				List<ProvideCommodityMove> comms= query.getResultList();
				lists.get(i).setCommoditys(comms);
			}
		}
		reMap.put("commoditys", lists);
		String jpql2="select new  guoanmaker.provider.business.modelnobind.ProvideRoomMove(rm.id,rm.roomName,rm.describeAsk,rm.address,rm.lat,"
				+ "rm.lng,c.name,a.name,p.name,rm.spaceDetail,rm.roomImgOne,rm.roomImgTwo,rm.roomImgThree,rm.roomImgFour,rm.roomImgFive,rm.roomlogo,rm.complement) "
				+ " from ProvideRoom rm left join rm.city c left join rm.area a"
				+ " left join rm.province p where rm.roomState=2 and rm.roomCodes=:roomCodes ";
		
		Query query2=manager.createQuery(jpql2);//查询商品信息
		query2.setParameter("roomCodes", roomCode);
		List<ProvideRoomMove> rooms= query2.getResultList();
		if(rooms.size()>0){
			ProvideRoomMove roomMove=rooms.get(0);
			String complement=roomMove.getComplement();//配套
			List<String> userList = Arrays.asList(complement.split(","));
			List<ProvideSpacefacilities> spacefacilities=provideSpacefacilitiesRepository.findByIdIn(userList);
			roomMove.setSpacefacilities(spacefacilities);
			reMap.put("room",roomMove);
		}else{
			reMap.put("room", null);
		}
		return reMap;
	}


	/***
	* @Title: selectByCommodityCode 
	* @Description: 通过商品code查询商品
	* @param commodityCode
	* @param cityCode 地级市code
	* @return ProvideCommodity    返回类型 
	* @throws 
	 */
	@Override
	public ProvideCommodityMove selectByCommodityCode(String commodityCode, String cityCode,String userId) {
		String jpql="select new guoanmaker.provider.business.modelnobind.ProvideCommodityMove( "
				+ "t.commodityName,b.businessName,t.isBargaining,t.startingPrice,d.dictName,t.invoiceMail,t.isTerritoryRestriction"
				+ ",t.commodityPrice,t.commodityPricePromotion,t.startTime,t.endTime,t.commodity_bigimage,t.description,t.commodityState,t.releaseTime,t.stock"
				+ ",t.populationRestriction,t.registrationStartTime,t.registrationEndTime,t.synopsis,t.id,t.type,sv.serverName,t.isPromotion,t.clickRate,t.process"
				+ ",t.promise,t.commodityCase,t.auditOpinion,t.finalPrice,t.introduce,t.commodity_smallimage,b.LicensPhone) "
				+ " from ProvideCommodity t  left  join t.providerBusiness b left join t.serviceType  sv"
				+ " left join t.measurementUnit d    where  t.commodityCode=:commodityCode ";
		Integer code=Integer.parseInt(commodityCode);
		Query query=manager.createQuery(jpql);//查询商品信息
		query.setParameter("commodityCode", code);
		List<ProvideCommodityMove> comms= query.getResultList();
		ProvideCommodityMove commodity=null;
		if(comms.size()>0){
			commodity=comms.get(0);
			String jpql2="select new guoanmaker.provider.business.modelnobind.ProvideCommodityServiceMove(s.id,ct.code,a.name,ct.name,p.name,ct.provincecode,s.isPromotion,s.commodityPrice,s.commodityPricePromotion,s.startTime,s.endTime,s.finalPrice)"
					+ " from ProvideCommodityServiceRange s left join  s.commodity c left join s.city ct left join s.area a left join s.province p  where  c.commodityCode=:commodityCode and ct.code=:code order by s.finalPrice";
			Query query2=manager.createQuery(jpql2);//查询商品提供的服务区域
			query2.setParameter("commodityCode", code);
			query2.setParameter("code", cityCode);
			List<ProvideCommodityServiceMove> lists=query2.getResultList();
			commodity.setServiceRange(lists);
			if(lists.size()>0){
				commodity.setFinalPrice(lists.get(0).getFinalPrice());
				if(lists.get(0).getIsPromotion()!=null){
					commodity.setIsPromotion(lists.get(0).getIsPromotion());
					commodity.setCommodityPrice(lists.get(0).getCommodityPrice());
				}
			}
			String commodityId=commodity.getId();
			if(StringUtils.isNotEmpty(userId)){
				List<PersonalCollection> commodityCollection=personalCollectionRepository.findByPersonalUser_idIsAndProvideCommodity_idIs(userId, commodityId);
				if(commodityCollection.size()>0){
					commodity.setIsCollection(1);
				}else{
					commodity.setIsCollection(2);
				}
			}else{
				commodity.setIsCollection(2);
			}
			commodity.setLicensPhone("4008518585");
		}
		
		return commodity;
	}


	/***
	* @Title: countCommditysClickRateByCode 
	* @Description: 统计商品的点击量
	* @param  commodityCode    商品code
	* @return void    返回类型 
	* @throws 
	 */
	@Override
	@Transactional
	public void countCommditysClickRateByCode(String commodityCode) {
			Integer code=Integer.parseInt(commodityCode);
			String hql="select s from ProvideCommodity s where s.commodityCode=:commodityCode";
			Query query=manager.createQuery(hql);//查询商品信息
			query.setParameter("commodityCode", code);
			ProvideCommodity comm=(ProvideCommodity) query.getSingleResult();
			if(comm!=null){
				Integer clickRate=comm.getClickRate();
				if(clickRate==null){
					clickRate=1;
				}else{
					clickRate++;
				}
				hql="update  ProvideCommodity set clickRate="+clickRate+" where commodityCode=:commodityCode";
				Query query2=manager.createQuery(hql);//修改点击量
				query2.setParameter("commodityCode", code);
				int result=query2.executeUpdate();
				System.out.println(result);
			}
		}


		
		
	/**
	* @Title: selectProvideCommodityRoomMoves 
	* @Description: 分页查询空间商品列表
	* @param  page 当前页
	* @param  size 显示条数
	* @param  service_type_id(类型)
	* @param  code 当前城市code
	* @param  regionStart 地区商品查询起始
	* @param  countrywideStart 全国商品查询起始
	* @param reorderType排序条件 0:默认查询 1:评价得分高低排序 2:点击量由高到低排序 3:按照商品价格由低到高排序 4:按照商品价格由高到低排序 5:按照商品销量由高到低排序
	* @param serverClass经营范围
	* @return Map<String,Object>    返回类型 
	* @throws 
	 */
	@Override
	public Map<String, Object> selectProvideCommodityRoomMoves(Integer page, Integer size, String service_type_id,
			String code, Integer regionStart, Integer countrywideStart, Integer reorderType,
			OperatorServerClass serverClass) {
		Map<String, Object> reMap=new HashMap<>();
		if(serverClass.getServerLevel()==2){
			//查询三级基础数据
			List<OperatorServerClass> servers=new ArrayList<>();
			servers=provideServerClassRepository.findAllByParentServerId(service_type_id);
			reMap.put("servers", servers);
		}
		String  serverId=serverClass.getId();//分类id
		String jpql="select new guoanmaker.provider.business.modelnobind.ProvideCommodityMove( "
				+ "t.commodityName,b.businessName,t.isBargaining,t.startingPrice,d.dictName,t.invoiceMail,t.isTerritoryRestriction"
				+ ",t.commodityPrice,t.commodityPricePromotion,t.startTime,t.endTime,t.commodity_bigimage,t.description,t.commodityState,t.releaseTime,t.stock"
				+ ",t.populationRestriction,t.registrationStartTime,t.registrationEndTime,t.synopsis,t.id,t.type,sv.serverName,t.isPromotion,t.clickRate,t.process"
				+ ",t.promise,t.commodityCase,t.auditOpinion,t.finalPrice,t.introduce,t.commodity_smallimage,b.LicensPhone,c.name,t.salesVolume) "
				+ " from ProvideCommodity t  left  join t.providerBusiness b left join t.serviceType  sv"
				+ " left join t.measurementUnit d left join t.romm rm left join rm.city c  where t.commodityState=2 and  c.code=:code and sv.id=:serverId";
		String sort1="";//全国排序规则
		if(reorderType==5){ //按照销量排序
			sort1=" order by t.salesVolume desc";
		}else if(reorderType==2){//按照点击量排序
			sort1=" order by t.clickRate desc";
		}else if(reorderType==3){
			sort1=" order by t.finalPrice asc";
		}else if(reorderType==4){
			sort1=" order by t.finalPrice desc";
		}else if(reorderType==1){
			sort1=" order by t.evaluateValue desc";
		}
		jpql=jpql+" group by t.id "+ sort1;
		Query query=manager.createQuery(jpql);//查询空间商品列表信息
		query.setParameter("code", code);
		query.setParameter("serverId", serverId);
		query.setMaxResults(size);
		query.setFirstResult((page-1)*size);
		List<ProvideCommodityMove> comms= query.getResultList();
		if(comms.size()==size){
			reMap.put("isLoading",1);
		}else{
			reMap.put("isLoading",2);
		}
		reMap.put("regionStart",0);
		reMap.put("countrywideStart",0);
		reMap.put("commoditys",comms);
		return reMap;
	}


	/***
	* @Title: selectByCommoditys 
	* @Description: 官网商品排行榜
	* @param  cityCode(城市code)
	* @param  type(查询条件 1；销量排序 2:成交价格排序)
	* @param  page(页数)
	* @param  size(条数)
	* @param @return    设定文件 
	* @return List<ProvideCommodityMove>    返回类型 
	* @throws 
	 */
	@Override
	public List<ProvideCommodityMove> selectByCommoditys(String cityCode, Integer type, Integer page, Integer size) {
		String order_by1="t1.salesVolume desc";
		String order_by11="t.salesVolume desc";
		if(type==2){
			order_by1="o.realPrice DESC";
			order_by11="o.realPrice DESC";
		}
		String jpql="select new guoanmaker.provider.business.modelnobind.ProvideCommodityMove("
				+ "t1.commodityName,b.businessName,t1.isBargaining,t1.startingPrice,d.dictName,t1.invoiceMail,t1.isTerritoryRestriction"
				+ ",t1.commodityPrice,t1.commodityPricePromotion,t1.startTime,t.endTime,t1.commodity_bigimage,t1.description,t1.commodityState,t1.releaseTime,t1.stock"
				+ ",t1.populationRestriction,t1.registrationStartTime,t1.registrationEndTime,t1.synopsis,t1.id,t1.type,sv.serverName,t1.isPromotion,t1.clickRate"
				+ ",b.companyCity,t1.commodity_smallimage,t1.salesVolume,MIN(t.finalPrice),t1.evaluateValue) from ProvideCommodityServiceRange t left join t.commodity t1 left join t.city c "
				+ "left join t1.providerBusiness b  left join t1.measurementUnit d   "
			+ "left join t1.serviceType sv left join  t1.orderforms o where t1.commodityState=2 and c.code=:code group by t1.id order by  "+order_by1;
		Query query=manager.createQuery(jpql);//查询商品列表
		query.setParameter("code", cityCode);
		query.setFirstResult((page-1)*size);
		query.setMaxResults(size);
		List<ProvideCommodityMove> commodityMoves=query.getResultList();
		if(commodityMoves.size()<size){
			String jql="select new guoanmaker.provider.business.modelnobind.ProvideCommodityMove("
					+ "t.commodityName,b.businessName,t.isBargaining,t.startingPrice,d.dictName,t.invoiceMail,t.isTerritoryRestriction"
					+ ",t.commodityPrice,t.commodityPricePromotion,t.startTime,t.endTime,t.commodity_bigimage,t.description,t.commodityState,t.releaseTime,t.stock"
					+ ",t.populationRestriction,t.registrationStartTime,t.registrationEndTime,t.synopsis,t.id,t.type,sv.serverName,t.isPromotion,t.clickRate"
					+ ",b.companyCity,t.commodity_smallimage,t.salesVolume,MIN(t.finalPrice),t.evaluateValue) "
					+ "from ProvideCommodity t left join t.providerBusiness b  left join t.measurementUnit d left join t.serviceType sv left join t.orderforms o"
					+ " where  t.commodityState=2 and t.isTerritoryRestriction='2' group by t.id order by  "+order_by11;
			int length=size-commodityMoves.size();//需要补充的个数
			query=manager.createQuery(jql);//查询商品列表
			query.setFirstResult((page-1)*size);
			query.setMaxResults(length);
			List<ProvideCommodityMove> commoditys=query.getResultList();
			if(commoditys.size()>0){
				for(int i=0;i<commoditys.size();i++){
					commodityMoves.add(commoditys.get(i));
				}
			}
		}
		return commodityMoves;
	}
}
